package com.wstuo.common.config.backup.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.backup.dto.BackupFileDTO;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.TimeUtils;

public class BuckUpFileService implements IBuckUpFileService {
	private static final Logger LOGGER = Logger.getLogger(BuckUpFileService.class );    
	/**
	 * 备份文件路径
	 */
	private static final String BACK_UP_PATH = AppConfigUtils.getInstance().getBackUpPath();
	@Autowired
	private DBXMLHelper dbxmlHelper;

	/**
	 * 取得备份文件列表.
	 */
	@Transactional
	public PageDTO showAllBackFiles() {
		PageDTO backupFiles = new PageDTO();
		DecimalFormat df = new DecimalFormat("#0.000");// 数字格式化
		List<BackupFileDTO> fileList = new ArrayList<BackupFileDTO>();
		File file = new File(BACK_UP_PATH);// 读取目录
		if (!file.exists()) {// 创建目录结构
			file.mkdirs();
		}
		File files[] = file.listFiles();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					String fileName = files[i].getName();
					if (fileName.indexOf(".sql") != -1) {
						String fileType = fileName.substring(fileName.lastIndexOf(".sql"), fileName.length());
						if (".sql".equals(fileType)) {// 只读取xml文件
							BackupFileDTO dto = new BackupFileDTO();
							dto.setFileName(fileName);// 备份名称
							dto.setCrateDate(TimeUtils.format(new Date(files[i].lastModified()),TimeUtils.DATETIME_PATTERN));// 创建时间
							dto.setFileSize(df.format(files[i].length() / 1048576.0000) + "MB");// 大小
							fileList.add(dto);
						}
					}
				}
			}
			if (fileList.size() > 0) {
				backupFiles.setData(fileList);
				backupFiles.setPage(1);
				backupFiles.setTotal(fileList.size());
				backupFiles.setTotalSize(fileList.size());
				backupFiles.setRows(fileList.size());
			}

		}
		return backupFiles;
	}

	/**
	 * 删除备份文件
	 */
	@Transactional
	public void deleteBackup(String[] fileNames) {
		if (fileNames != null && fileNames.length > 0) {
			for (String fileName : fileNames) {
				File f = new File(BACK_UP_PATH + "/" + fileName);
				if (f.exists()) {
					f.delete();
				}
			}
		}
	}

	/**
	 * 创建备份文件
	 */
	@Transactional
	public String createBackup() {
		Long siz = 0L;
		Long size = 0L;
		try {
			String filedata = TimeUtils.format(new Date(), "yyyy_MM_dd_HH_mm_ss");
			String fileSql = BACK_UP_PATH + "/db_backup_" + filedata + ".sql";
			dbxmlHelper.exportDatabase(fileSql);
			siz = new File(fileSql).length();
			Thread.sleep(5000);
			size = new File(fileSql).length();
			while (true) {
				if (!siz.equals(size)) {
					siz = size;
					Thread.sleep(3000);
					size = new File(fileSql).length();
				} else {
					break;
				}
			}
		} catch (Exception e) {
			throw new ApplicationException("ERROR_SQL_FILE_BACKUP");
		}

		return siz.toString();
	}
	/**
	 * 还原数据库.
	 */
	@Transactional
	public void restoreBackup(String fileName) {
		try {
			dbxmlHelper.refreshData(BACK_UP_PATH + "/" + fileName);
		} catch (Exception e) {
			throw new ApplicationException("ERROR_BACKUP_RESTORE_FAILURE", e);
		}
	}
	/**
	 * 下载备份文件.
	 */
	@Transactional
	public InputStream download(String fileName){
		InputStream downloadStream = null;
		try {
			downloadStream = new FileInputStream(new File(BACK_UP_PATH+"/"+fileName));
		} catch (FileNotFoundException e) {
			LOGGER.error("BuckUpFileAction download",e);
		}
		return  downloadStream;
	}
}
